package client.controller;

import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.net.Socket;

import javax.imageio.ImageIO;
import javax.imageio.ImageReader;

public class ImageSynchronizeClient {

	private String[] ImageFileName;
	private File repertoire;
	
	public ImageSynchronizeClient (String dirRep, int nbIm) {
		this.ImageFileName = new String [nbIm];
		this.deleteDirectory(dirRep);	
		this.repertoire = new File(dirRep);
		
	}
	
	public void receptionImage(Socket client) throws IOException{
		int i = 0;
		
		BufferedInputStream locBufferedInputStream = new BufferedInputStream(client.getInputStream());
		
		while (true) {
			File file = new File(this.repertoire+"/"+this.ImageFileName[i]);
			System.out.println("AVANT Repertoire : "+this.repertoire + ";"+this.ImageFileName[i]);
			
			//file.createNewFile();
			String locFormat = this.ImageFileName[i].substring(this.ImageFileName[i].indexOf(".") + 1, this.ImageFileName[i].length());
			
			byte[] locImageByte = null;
			locImageByte = new byte[locBufferedInputStream.available()];
			
			System.out.println("LA 1"+ file + locFormat + locImageByte);
			
			locBufferedInputStream.read(locImageByte);
			System.out.println("LA 1BIS "+locBufferedInputStream);
			
			//Image "corrompue"
			BufferedImage locImage = ImageIO.read(locBufferedInputStream);
			System.out.println("LA 2"+ file + locFormat + locImage);
			
			ImageIO.write(locImage, locFormat, file);
			System.out.println("APRES Repertoire : "+this.repertoire + ";" +this.ImageFileName[i]);
			locImage.flush();
			i++;
			if( i == this.ImageFileName[i].length()) {
				break;
			}
		}
	}
	
	public void setImageFileName(int i, String idImage) {
		System.out.println("setImage nom : "+idImage + " indTab : "+i);
		this.ImageFileName[i] = idImage;
	}
	
	public String getImageTab(int i) {
		return ImageFileName[i];
	}
	
	public String [] getTabImage() {
		return this.ImageFileName;
	}
	
	public void deleteDirectory(String emplacement) {
		 
		File path = new File(emplacement);
	    if( path.exists() ) {
	      File[] files = path.listFiles();
	      for(int i=0; i<files.length; i++) {
	         if(files[i].isDirectory()) {
	           deleteDirectory(path+"\\"+files[i]);
	         }
	         else {
	           files[i].delete();
	         }
	      }
	    }
	  }
}
